<template>
  <div class="user-permissions">
    <!-- 头部导航 -->
    <el-card class="header-card" shadow="hover">
      <div class="header-content">
        <div class="header-left">
          <el-button type="primary" @click="goBack" plain>
            <el-icon><ArrowLeft /></el-icon>
            返回详情
          </el-button>
          <el-divider direction="vertical" />
          <el-icon class="header-icon"><Key /></el-icon>
          <span class="header-title">权限管理</span>
        </div>
        <div class="header-actions">
          <el-button type="success" @click="handleSave" :loading="saveLoading">
            <el-icon><Check /></el-icon>
            保存权限
          </el-button>
          <el-button type="info" @click="handleReset">
            <el-icon><RefreshLeft /></el-icon>
            重置
          </el-button>
        </div>
      </div>
    </el-card>

    <el-row :gutter="20" v-loading="loading">
      <!-- 用户信息 -->
      <el-col :span="8">
        <el-card class="user-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <el-icon><User /></el-icon>
              <span>用户信息</span>
            </div>
          </template>
          
          <div class="user-info">
            <el-avatar
              :src="userInfo.avatar"
              :size="80"
              class="user-avatar"
            >
              {{ userInfo.username?.charAt(0) }}
            </el-avatar>
            
            <div class="user-details">
              <h3>{{ userInfo.username }}</h3>
              <p class="user-username">@{{ userInfo.username }}</p>
              <div class="user-tags">
                <el-tag type="primary" size="small">{{ getUserRoleNames() || '暂无角色' }}</el-tag>
                <el-tag :type="userInfo.status === 'enabled' ? 'success' : 'danger'" size="small">
                  {{ userInfo.status === 'enabled' ? '启用' : '禁用' }}
                </el-tag>
              </div>
              
              <el-descriptions :column="1" size="small" class="user-desc">
                <el-descriptions-item label="邮箱">
                  {{ userInfo.email || '-' }}
                </el-descriptions-item>
                              <el-descriptions-item label="手机号">
                {{ userInfo.mobile || '-' }}
              </el-descriptions-item>
                <el-descriptions-item label="所属客户">
                  {{ userInfo.customerName || '系统用户' }}
                </el-descriptions-item>
                <el-descriptions-item label="创建时间">
                  {{ formatDateTime(userInfo.createdAt) }}
                </el-descriptions-item>
              </el-descriptions>
            </div>
          </div>
        </el-card>

        <!-- 角色权限概览 -->
        <el-card class="role-overview-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <el-icon><UserFilled /></el-icon>
              <span>角色权限概览</span>
            </div>
          </template>
          
          <div class="role-overview">
            <div v-if="userInfo.roles && userInfo.roles.length > 0" class="current-role">
              <div class="role-info">
                <h4>{{ getUserRoleNames() }}</h4>
                <p class="role-code">{{ getUserRoleCodes() }}</p>
                <p class="role-desc">{{ getUserRoleDescriptions() }}</p>
              </div>
              
              <!-- 权限统计圆球 -->
              <div class="permission-stats">
                <div class="stat-item">
                  <div class="stat-circle total">
                    <span class="stat-number">{{ totalPermissions }}</span>
                    <span class="stat-label">总权限</span>
                  </div>
                </div>
                <div class="stat-item">
                  <div class="stat-circle granted">
                    <span class="stat-number">{{ grantedPermissions }}</span>
                    <span class="stat-label">已授权</span>
                  </div>
                </div>
                <div class="stat-item">
                  <div class="stat-circle denied">
                    <span class="stat-number">{{ deniedPermissions }}</span>
                    <span class="stat-label">已拒绝</span>
                  </div>
                </div>
              </div>
            </div>
            <div v-else class="no-role">
              <el-empty description="用户尚未分配角色" :image-size="60" />
            </div>
          </div>
        </el-card>
      </el-col>

      <!-- 权限管理主区域 -->
      <el-col :span="16">
        <el-card class="permissions-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <div class="header-left">
                <el-icon><Lock /></el-icon>
                <span>权限配置</span>
              </div>
              <div class="header-actions">
                <el-button-group>
                  <el-button 
                    :type="viewMode === 'tree' ? 'primary' : ''"
                    @click="viewMode = 'tree'"
                    size="small"
                  >
                    <el-icon><Operation /></el-icon>
                    树形视图
                  </el-button>
                  <el-button 
                    :type="viewMode === 'list' ? 'primary' : ''"
                    @click="viewMode = 'list'"
                    size="small"
                  >
                    <el-icon><List /></el-icon>
                    列表视图
                  </el-button>
                </el-button-group>
                <el-button size="small" @click="expandAll">
                  <el-icon><FolderOpened /></el-icon>
                  全部展开
                </el-button>
                <el-button size="small" @click="collapseAll">
                  <el-icon><Folder /></el-icon>
                  全部收起
                </el-button>
              </div>
            </div>
          </template>

          <!-- 搜索过滤 -->
          <div class="permission-filter">
            <el-input
              v-model="filterText"
              placeholder="搜索权限名称或描述"
              prefix-icon="Search"
              clearable
              style="width: 300px;"
            />
          </div>

          <!-- 权限树形视图 -->
          <div v-if="viewMode === 'tree'" class="permissions-tree">
            <div v-if="!filteredPermissions || filteredPermissions.length === 0" class="empty-permissions">
              <el-empty 
                :description="getEmptyDescription()" 
                :image-size="100"
              >
                <template #description>
                  <div class="empty-description">
                    <p>{{ getEmptyDescription() }}</p>
                    <p v-if="filterText.value" class="filter-tip">
                      {{ getFilterTip() }}
                    </p>
                  </div>
                </template>
                <el-button type="primary" @click="loadPermissions">
                  <el-icon><RefreshLeft /></el-icon>
                  重新加载
                </el-button>
                <el-button v-if="filterText.value" @click="clearFilters" style="margin-left: 10px;">
                  <el-icon><Delete /></el-icon>
                  清除筛选
                </el-button>
              </el-empty>
            </div>
            <el-tree
              v-else
              ref="permissionTreeRef"
              :data="filteredPermissions"
              :props="treeProps"
              show-checkbox
              node-key="id"
              :default-checked-keys="checkedPermissions"
              :default-expanded-keys="expandedKeys"
              @check-change="handlePermissionChange"
              class="permission-tree"
            >
              <template #default="{ data }">
                <div class="tree-node">
                  <div class="node-content">
                    <el-icon v-if="data.type === 'module'" class="node-icon module-icon">
                      <Folder />
                    </el-icon>
                    <el-icon v-else-if="data.type === 'menu'" class="node-icon menu-icon">
                      <Menu />
                    </el-icon>
                    <el-icon v-else class="node-icon permission-icon">
                      <Key />
                    </el-icon>
                    <span class="node-label">{{ data.name }}</span>
                    <el-tag v-if="data.code && data.code !== data.name" size="small" type="info" class="node-code">
                      {{ data.code }}
                    </el-tag>
                  </div>
                </div>
              </template>
            </el-tree>
          </div>

          <!-- 权限列表视图 -->
          <div v-if="viewMode === 'list'" class="permissions-list">
            <el-table
              :data="flatPermissions"
              @selection-change="handleTableSelectionChange"
              class="permission-table"
            >
              <el-table-column type="selection" width="55" />
              <el-table-column prop="name" label="权限名称" min-width="200">
                <template #default="{ row }">
                  <div class="permission-name">
                    <el-icon v-if="row.type === 'module'" class="module-icon">
                      <Folder />
                    </el-icon>
                    <el-icon v-else-if="row.type === 'menu'" class="menu-icon">
                      <Menu />
                    </el-icon>
                    <el-icon v-else class="permission-icon">
                      <Key />
                    </el-icon>
                    <span>{{ row.name }}</span>
                  </div>
                </template>
              </el-table-column>
              <el-table-column prop="code" label="权限代码" width="150">
                <template #default="{ row }">
                  <el-tag v-if="row.code" size="small" type="info">{{ row.code }}</el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="type" label="类型" width="100">
                <template #default="{ row }">
                  <el-tag :type="getTypeColor(row.type)" size="small">
                    {{ getTypeName(row.type) }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="description" label="描述" min-width="200" />
              <el-table-column label="状态" width="100">
                <template #default="{ row }">
                  <el-tag 
                    :type="checkedPermissions.includes(row.id) ? 'success' : 'info'" 
                    size="small"
                  >
                    {{ checkedPermissions.includes(row.id) ? '已授权' : '未授权' }}
                  </el-tag>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, watch } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import {
  ArrowLeft, Key, Check, RefreshLeft, User, UserFilled, DataAnalysis, Lock,
  Operation, List, FolderOpened, Folder, Menu, Delete
} from '@element-plus/icons-vue';
import UserAPI from '@/api/system/user.api';
import PermissionAPI from '@/api/system/permission.api';
import { formatDateTime } from '@/utils/date';

const router = useRouter();
const route = useRoute();

// 视图模式
const viewMode = ref('tree');

// 数据状态
const loading = ref(false);
const saveLoading = ref(false);

// 用户信息
const userInfo = ref({});

// 权限数据
const permissions = ref([]);
const checkedPermissions = ref([]);
const expandedKeys = ref([]);

// 过滤
const filterText = ref('');

// 树形组件引用
const permissionTreeRef = ref();

// 树形配置
const treeProps = {
  children: 'children',
  label: 'name',
  value: 'id'
};

// 计算属性
const filteredPermissions = computed(() => {
  let result = permissions.value;
  
  if (filterText.value) {
    result = filterPermissions(result, filterText.value);
  }
  
  return result;
});

const flatPermissions = computed(() => {
  return flattenPermissions(filteredPermissions.value);
});

const totalPermissions = computed(() => {
  const total = flatPermissions.value.length;
  console.log('总权限计算:', {
    过滤后权限: filteredPermissions.value,
    展平后权限: flatPermissions.value,
    总权限数: total
  });
  return total;
});

const grantedPermissions = computed(() => {
  // 只计算叶子节点的已授权权限
  const leafPermissionIds = flatPermissions.value.map(p => p.id);
  const granted = checkedPermissions.value.filter(id => leafPermissionIds.includes(id)).length;
  
  console.log('已授权计算:', {
    用户权限ID列表: checkedPermissions.value,
    叶子权限ID列表: leafPermissionIds,
    已授权数: granted
  });
  
  return granted;
});

const deniedPermissions = computed(() => {
  const denied = totalPermissions.value - grantedPermissions.value;
  return Math.max(0, denied); // 确保不会出现负数
});

// 监听过滤条件变化
watch([filterText], () => {
  // 重新设置展开的节点
  expandedKeys.value = getExpandedKeys(filteredPermissions.value);
});

// 过滤权限
const filterPermissions = (permissions, text) => {
  const filtered = [];
  
  for (const permission of permissions) {
    const matchText = permission.name.toLowerCase().includes(text.toLowerCase()) ||
                     (permission.description && permission.description.toLowerCase().includes(text.toLowerCase())) ||
                     (permission.code && permission.code.toLowerCase().includes(text.toLowerCase()));
    
    if (matchText) {
      filtered.push(permission);
    } else if (permission.children && permission.children.length > 0) {
      const filteredChildren = filterPermissions(permission.children, text);
      if (filteredChildren.length > 0) {
        filtered.push({
          ...permission,
          children: filteredChildren
        });
      }
    }
  }
  
  return filtered;
};

// 展平权限树
const flattenPermissions = (permissions) => {
  const result = [];
  
  const flatten = (items, level = 0) => {
    for (const item of items) {
      // 只计算叶子节点（没有子节点的权限）
      if (!item.children || item.children.length === 0) {
        result.push({ ...item, level });
      } else {
        // 如果有子节点，递归处理子节点
        flatten(item.children, level + 1);
      }
    }
  };
  
  flatten(permissions);
  return result;
};

// 获取展开的键
const getExpandedKeys = (permissions) => {
  const keys = [];
  
  const getKeys = (items) => {
    for (const item of items) {
      if (item.children && item.children.length > 0) {
        keys.push(item.id);
        getKeys(item.children);
      }
    }
  };
  
  getKeys(permissions);
  return keys;
};

// 获取类型颜色
const getTypeColor = (type) => {
  const colorMap = {
    module: 'primary',
    menu: 'success',
    button: 'warning',
    api: 'info'
  };
  return colorMap[type] || 'info';
};

// 获取类型名称
const getTypeName = (type) => {
  const nameMap = {
    module: '模块',
    menu: '菜单',
    button: '按钮',
    api: '接口'
  };
  return nameMap[type] || '未知';
};

// 全部展开
const expandAll = () => {
  expandedKeys.value = getExpandedKeys(permissions.value);
};

// 全部收起
const collapseAll = () => {
  expandedKeys.value = [];
};

// 权限变化处理
const handlePermissionChange = (data, checked, indeterminate) => {
  console.log('权限变化:', data, checked, indeterminate);
  // 获取当前选中的权限
  const checkedNodes = permissionTreeRef.value.getCheckedNodes();
  checkedPermissions.value = checkedNodes.map(node => node.id);
};

// 表格选择变化
const handleTableSelectionChange = (selection) => {
  checkedPermissions.value = selection.map(item => item.id);
};

// 加载用户信息
const loadUserInfo = async () => {
  try {
    const userId = route.params.id;
    if (!userId) {
      ElMessage.error('用户ID不能为空');
      goBack();
      return;
    }

    const res = await UserAPI.getById(userId);
    if (res && res.data) {
      userInfo.value = res.data;
    } else if (res) {
      userInfo.value = res;
    }

    // 角色信息已经包含在userInfo.roles中，无需额外加载
  } catch (error) {
    ElMessage.error('加载用户信息失败: ' + (error.message || error));
    console.error('加载用户信息失败:', error);
  }
};

// 获取用户角色名称
const getUserRoleNames = () => {
  if (userInfo.value.roles && userInfo.value.roles.length > 0) {
    return userInfo.value.roles.map(role => role.name).join(', ');
  }
  return null;
};

// 获取用户角色代码
const getUserRoleCodes = () => {
  if (userInfo.value.roles && userInfo.value.roles.length > 0) {
    return userInfo.value.roles.map(role => role.code).join(', ');
  }
  return null;
};

// 获取用户角色描述
const getUserRoleDescriptions = () => {
  if (userInfo.value.roles && userInfo.value.roles.length > 0) {
    const descriptions = userInfo.value.roles
      .map(role => role.description)
      .filter(desc => desc && desc.trim() !== '')
      .join('; ');
    
    // 如果角色没有描述，尝试显示权限描述
    if (!descriptions) {
      // 获取用户权限描述
      const permissionDescriptions = permissions.value
        .filter(perm => checkedPermissions.value.includes(perm.id))
        .map(perm => perm.description)
        .filter(desc => desc && desc.trim() !== '')
        .slice(0, 3) // 只显示前3个权限描述
        .join('; ');
      
      return permissionDescriptions || '暂无描述';
    }
    
    return descriptions;
  }
  return null;
};

// 加载权限数据
const loadPermissions = async () => {
  loading.value = true;
  try {
    console.log('开始加载权限数据...');
    
    // 优先从权限树API获取数据
    const res = await PermissionAPI.getTree();
    console.log('权限树API响应:', res);
    
    let permissionData = res.data || res || [];
    console.log('解析后的权限数据:', permissionData);
    
    // 如果权限树为空，显示空状态
    if (!permissionData || permissionData.length === 0) {
      console.log('权限树为空，显示空状态');
      console.warn('权限树API返回空数据，请检查后端接口');
      permissionData = [];
    }
    
    permissions.value = permissionData;
    console.log('设置到permissions.value:', permissions.value);
    
    // 如果还是没有数据，显示空状态
    if (!permissions.value || permissions.value.length === 0) {
      console.log('权限数据为空，显示空状态');
      console.error('权限数据加载失败，请检查网络连接和API接口');
      permissions.value = [];
    }

    // 加载用户已有权限
    const userPermRes = await UserAPI.getUserPermissions(route.params.id);
    console.log('用户权限API响应:', userPermRes);
    checkedPermissions.value = userPermRes.data || userPermRes || [];
    console.log('用户已有权限ID列表:', checkedPermissions.value);
    
    // 默认展开所有节点
    expandedKeys.value = getExpandedKeys(permissions.value);
    
    console.log('权限数据加载完成:', {
      权限树节点数: permissions.value.length,
      用户权限数: checkedPermissions.value.length,
      展开节点数: expandedKeys.value.length,
      过滤后权限数: filteredPermissions.value.length,
      搜索文本: filterText.value
    });
    
    // 如果没有权限数据，显示提示
    if (permissions.value.length === 0) {
      ElMessage.warning('权限数据加载失败，请检查网络连接或联系管理员');
    }
  } catch (error) {
    ElMessage.error('加载权限数据失败: ' + (error.message || error));
    console.error('加载权限数据失败:', error);
    console.error('错误详情:', {
      message: error.message,
      stack: error.stack,
      response: error.response
    });
  } finally {
    loading.value = false;
  }
};

// 保存权限
const handleSave = async () => {
  try {
    await ElMessageBox.confirm(
      '确定要保存用户权限配置吗？',
      '保存确认',
      {
        confirmButtonText: '确定保存',
        cancelButtonText: '取消',
        type: 'info',
      }
    );
    
    saveLoading.value = true;
    
    const saveData = {
      userId: userInfo.value.id,
      permissionIds: checkedPermissions.value
    };
    
    // await UserAPI.saveUserPermissions(saveData);
    
    ElMessage.success('权限保存成功');
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('保存失败: ' + (error.message || error));
    }
  } finally {
    saveLoading.value = false;
  }
};

// 重置权限
const handleReset = async () => {
  try {
    await ElMessageBox.confirm(
      '确定要重置权限配置吗？所有修改将丢失！',
      '重置确认',
      {
        confirmButtonText: '确定重置',
        cancelButtonText: '取消',
        type: 'warning',
      }
    );
    
    await loadPermissions();
    ElMessage.success('权限已重置');
  } catch (error) {
    // 用户取消，不做处理
  }
};

// 返回详情
const goBack = () => {
  router.push({ path: `/system/user/detail/${route.params.id}` });
};

// 获取空状态描述
const getEmptyDescription = () => {
  if (filterText.value) {
    return '未找到符合条件的权限数据';
  }
  return '暂无权限数据';
};

// 获取筛选提示
const getFilterTip = () => {
  if (filterText.value) {
    return `名称/描述包含"${filterText.value}"`;
  }
  return '';
};

// 清除筛选
const clearFilters = () => {
  filterText.value = '';
};

// 页面加载完成后执行
onMounted(() => {
  console.log('权限管理页面加载完成');
  console.log('路由参数:', route.params);
  console.log('用户ID:', route.params.id);
  
  if (route.params.id) {
    loadUserInfo();
    loadPermissions();
  } else {
    ElMessage.error('用户ID不能为空');
  }
});
</script>

<style scoped>
.user-permissions {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.header-card {
  margin-bottom: 20px;
  border-radius: 8px;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 10px;
}

.header-icon {
  font-size: 18px;
  color: #409eff;
}

.header-title {
  font-size: 18px;
  font-weight: 600;
  color: #333;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.user-card,
.role-overview-card,
.permissions-card {
  margin-bottom: 20px;
  border-radius: 8px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: 600;
  color: #333;
}

.card-header > div:first-child {
  display: flex;
  align-items: center;
  gap: 8px;
}

.card-header .el-icon {
  font-size: 16px;
  color: #409eff;
}

.user-info {
  text-align: center;
}

.user-avatar {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  font-weight: 600;
  margin-bottom: 15px;
}

.user-details h3 {
  margin: 10px 0 5px;
  color: #333;
  font-size: 18px;
}

.user-username {
  color: #909399;
  margin: 5px 0 10px;
  font-size: 14px;
}

.user-tags {
  margin: 10px 0;
}

.user-tags .el-tag {
  margin: 2px;
}

.user-desc {
  text-align: left;
  margin-top: 15px;
}

.role-overview {
  text-align: center;
}

.current-role .role-info h4 {
  margin: 0 0 5px;
  color: #333;
  font-size: 16px;
}

.role-code {
  color: #409eff;
  font-size: 12px;
  margin: 5px 0;
}

.role-desc {
  color: #666;
  font-size: 13px;
  margin: 10px 0 20px;
}

/* 权限统计样式 */
.permission-stats {
  display: flex;
  justify-content: space-around;
  margin-top: 20px;
  padding: 15px 0;
  border-top: 1px solid #f0f0f0;
}

.stat-item {
  text-align: center;
}

.stat-circle {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  margin: 0 auto 8px;
  color: white;
  font-weight: 600;
}

.stat-circle.total {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.stat-circle.granted {
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
}

.stat-circle.denied {
  background: linear-gradient(135deg, #fa709a 0%, #fee140 100%);
}

.stat-number {
  font-size: 18px;
  font-weight: bold;
  line-height: 1;
}

.stat-label {
  font-size: 10px;
  margin-top: 2px;
  opacity: 0.9;
}

.permission-filter {
  margin-bottom: 20px;
  display: flex;
  align-items: center;
}

.permissions-tree,
.permissions-list {
  max-height: 600px;
  overflow-y: auto;
}

.permission-tree {
  width: 100%;
}

.tree-node {
  flex: 1;
  display: flex;
  flex-direction: column;
  padding: 4px 0;
}

.node-content {
  display: flex;
  align-items: center;
  gap: 8px;
}

.node-icon {
  font-size: 14px;
}

.module-icon {
  color: #409eff;
}

.menu-icon {
  color: #67c23a;
}

.permission-icon {
  color: #e6a23c;
}

.node-label {
  font-weight: 500;
  color: #333;
}

.node-code {
  margin-left: auto;
}

/* 移除可能导致重影的描述样式 */

.permission-table {
  width: 100%;
}

.empty-permissions {
  text-align: center;
  padding: 40px 20px;
}

.empty-description {
  color: #909399;
  font-size: 14px;
  line-height: 1.6;
}

.filter-tip {
  margin-top: 10px;
  color: #606266;
  font-size: 13px;
}

.permission-name {
  display: flex;
  align-items: center;
  gap: 8px;
}

.permission-name .el-icon {
  font-size: 14px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .user-permissions {
    padding: 10px;
  }
  
  .header-content {
    flex-direction: column;
    gap: 10px;
  }
  
  .header-actions {
    width: 100%;
    justify-content: center;
  }
  
  .permission-stats {
    flex-direction: column;
    gap: 15px;
  }
  
  .stat-circle {
    width: 60px;
    height: 60px;
  }
  
  .stat-number {
    font-size: 18px;
  }
}

/* 动画效果 */
.el-card {
  transition: all 0.3s ease;
}

.el-card:hover {
  box-shadow: 0 2px 20px rgba(0, 0, 0, 0.1);
}

.stat-circle {
  transition: all 0.3s ease;
}

.stat-circle:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
}

.tree-node {
  transition: all 0.3s ease;
}

.tree-node:hover {
  background-color: #f5f7fa;
}
</style>
